<?php
/**
 * Created by PhpStorm.
 * User: kun
 * Date: 26/6/19
 * Time: 18:20
 */

namespace app\api\controller\v1;


use app\api\controller\Common;
use app\common\lib\Aes;
use app\common\lib\exception\ApiException;
use app\common\lib\IAuth;

/**
 * 客户端auth登陆权限基础类库
 * 1.每个接口（需要登陆端接口 个人中心 点赞 评论）都需要继承
 * 2.判断 access_user_token 是否合法
 * 3.用户信息 => user
 * Class AuthBase
 * @package app\api\controller\v1
 */
class AuthBase extends Common
{
    //登陆用户的基本信息
    public $user = [];

    /**
     * 初始化的方法
     */
    public function _initialize()
    {
        parent::_initialize();
        if (!$this->isLogin()) {
            throw  new ApiException('您没有登陆', 401);
        }

    }

    /**
     * app判断用户是否登陆
     */
    public function isLogin()
    {
        if (empty($this->headers['access-user-token'])) {
            return false;
        }

        $obj = new Aes();
        $accessUserToken = $obj->decrypt($this->headers['access-user-token']);


        if (empty($accessUserToken)) {
            return false;
        }

        if (!preg_match('/||/', $accessUserToken)) {
            return false;
        }
        list($token, $id) = explode("||", $accessUserToken);

        $user = \app\common\model\User::get(['token' => $token]);
        if (!$user || $user->status != config('code.app_status_success')) {
            return false;
        }

        //判断时间是否过期
        if (time() > $user->time_out) {
            return false;
        }

        $this->user = $user;

        return true;

    }

    /**
     * app修改用户数据
     */
    public function update()
    {
        $data = [];
        $postData = input('param.');
        $validate = validate('User');

        if (!$validate->check($postData)) {
            return $this->error($validate->getError());
        }
        if (!empty($postData['image'])) {
            $data['image'] = $postData['image'];
        }
        if (!empty($postData['username'])) {
            $data['username'] = $postData['username'];
        }
        if (!empty($postData['sex'])) {
            $data['sex'] = $postData['sex'];
        }
        if (!empty($postData['signature'])) {
            $data['signature'] = $postData['signature'];
        }
        if (!empty($postData['password'])) {
            //传输过程中也需要加密处理的
            $data['password'] = IAuth::setPassword($postData['password']);
        }
        if (empty($data)) {
            return show(config('code.error'), '数据不合法', [], 404);
        }

        try {
            $id = model('User')->save($data, ['id' => $this->user->id]);
            if ($id) {
                return show(config('code.success'), 'ok', [], 202);
            } else {
                return show(config('code.error'), '更新失败', [], 401);
            }
        } catch (\Exception $e) {
            return show(config('code.error'), $e->getMessage(), [], 404);
        }

    }


}

